package hn.info.hockeynews.activities;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Timer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import hn.info.hockeynews.R;
import hn.info.hockeynews.dao.DaoMaster;
import hn.info.hockeynews.dao.Entry;
import hn.info.hockeynews.dao.EntryDao;
import hn.info.hockeynews.dao.DaoMaster.DevOpenHelper;
import hn.info.hockeynews.helpers.DBHelperEntries;
import hn.info.hockeynews.helpers.JSONAsync;
import hn.info.hockeynews.service.DatabaseService;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SimpleCursorAdapter;
import android.app.Activity;
import android.app.ListActivity;
import android.database.Cursor;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;

public class LivetickerActivity extends ListActivity {

	// = 164;
	private Cursor mCursor;
	private EntryDao entryDao;
	private List<Entry> listEntries;
	private ListAdapter adapter;
	private DBHelperEntries dbh;
	private DatabaseService dbs;
	private JSONAsync as;
	private DevOpenHelper helper;
	private long match_id;
	private String home;
	private String away;
	private List<String> tmplist;
	
	private int ptAway;
	private int ptHome;
	
	private Timer timer;
	
	private final Handler _handler = new Handler();
	private static int DATA_INTERVAL = 10;

	private final Runnable getData = new Runnable()
	{
	    @Override
	    public void run()
	    {
	        fetchJSON();
	    }
	};
	private void getDataFrame() 
	{
	    _handler.postDelayed(getData, DATA_INTERVAL);
	}
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        dbh = new DBHelperEntries();
        
        Bundle extras = getIntent().getExtras();

        match_id = extras.getLong("match_id");
        home = extras.getString("hometeam");
        away = extras.getString("awayteam");
        Log.d("id", "Fetch for: "+String.valueOf(match_id));

        
        
		if(dbh.checkData(match_id).equals("null"))
		{
     	 
	       // getDataFrame();
		if(dbh.checkData(match_id).equals("null")) {
			fetchJSON();
			Collections.reverse(this.tmplist);
	        adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, tmplist);
	    }
	    else {
	    	List<Integer> ints = new ArrayList<Integer>();
	        for(int i = 0; i < 400; i++) {
	        	ints.add(i);
	        }
	        adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, ints);
	    }
        setContentView(R.layout.activity_liveticker);
        setListAdapter(adapter);
		}
	}

	public void setMatch_id(long match_id) {
		this.match_id = match_id;
	}
	
	public long getMatch_id() {
		return match_id;
	}
	
	/**
	 * with this method you fetch the match data from the server into the database
	 * 
	 * */
	public void fetchJSON() {
		as = new JSONAsync();
		as.setUrl("http://hockey-news.info/androidapp/index.php");
		as.setTag("getTickerEntries");
		as.settId(String.valueOf(match_id));
		JSONObject obj = as.getData();
		try {
			JSONArray menuitemArray = obj.getJSONArray("matches");
			for (int y = 0; y < menuitemArray.length(); y++) {
				JSONObject mob = menuitemArray.getJSONObject(y);
	 			JSONObject e1 = mob.getJSONObject("entry");
	 			Timestamp tstamp = new Timestamp(System.currentTimeMillis()); 
	 			Entry e = new Entry(e1.getLong("entry_id"), e1.getLong("match_id"), e1.getInt("entry_type"), e1.getInt("team"), e1.getString("playtime"),
	 								e1.getString("player1"), e1.getString("player2"), e1.getString("player3"), e1.getInt("powerplay"), e1.getInt("penalty_time"), 
	 								e1.getString("penalty_reason"), e1.getInt("penalty_extension"), e1.getString("info"), e1.getString("entry_time"), tstamp);
	 			helper = new DaoMaster.DevOpenHelper(this, "entries-db", null);
	 			dbh.insertEntry(e, helper);
	 		}
		}
		catch (JSONException e) {
			e.printStackTrace();
	 	}
		if(String.valueOf(getMatch_id()) != null) {
			tmplist = new ArrayList<String>();
		    listEntries = dbh.getEntryData(match_id, helper);
		    this.ptAway = 0;
		    this.ptHome = 0;
		    for(Entry e : listEntries) {
		    	String text = "";
		        if(e.getTeam() ==1) {
		        	if (e.getEntry_type() == 1) {
		        		ptAway++;
		        	}
		        	text = e.getPlaytime() + " | " + ptHome + ":" + ptAway + " | " + this.away + " | " + e.getInfo();
		        }
		        if(e.getTeam() == 0) {
		        	if (e.getEntry_type() == 1) {
		        		ptHome++;
		        	}
		        	text = e.getPlaytime() + " | " + ptHome + ":" + ptAway + " | " + this.home + " | " + e.getInfo();
		        }
		        if(e.getTeam() == 2) {
		        	text = e.getPlaytime() + " | " + ptHome + ":" + ptAway + " |             | " + e.getInfo();
		        }
		        tmplist.add(text);
		    }
	    }
    }
	
	public int getPtAway() {
		return this.ptAway;
	}
	
	public void setPtAway(int ptAway) {
		this.ptAway = ptAway;
	}
	
	public int getPtHome() {
		return this.ptHome;
	}
	
	public void setPtHome(int ptHome) {
		this.ptHome = ptHome;
	}
}
